import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, message, Tree, Spin } from 'antd';
import { ColumnProps } from 'antd/es/table';
const { Option } = Select;
const { TreeNode, DirectoryTree } = Tree;
import axios from 'axios';
import * as moment from 'moment';
import './index.scss';
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';
import {isHavePathPermission} from '../../utils/utils'
import { forEach } from "lodash";
import { dynamicsService } from "../../../../../services/services";
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
  description: string;
}

const layout = {
  labelCol: {
    span: 4,

  },
  wrapperCol: {
    offset: 1,
    span: 19,
  },
}
const phoneValidator = (rule: any, value: any, callback: any) => {
  
  
  if (!value) {
    callback('请输入！')
  }
  // 必须总是返回一个 callback，否则 validateFields 无法响应
  callback();
}

const columns: ColumnProps<DataType>[] = [
  {
    title: '名称',
    dataIndex: 'Name',
    key: 'Name',
    align: 'center',
    render(text, recod: any) {
      
      const dispUrl = ListGUID.DocumentLink;
      const splitName = recod.Name.split('.');
      return (
        <div key={recod.UniqueId}>
          {
            splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + recod.UniqueId} target="_blank">{recod.Name}</a> : <a href={recod.ServerRelativeUrl} download={recod.Name} target="_blank">{recod.Name}</a>
          }
        </div>
      );
    },
  },
  {
    title: '修改时间',
    dataIndex: 'TimeLastModified',
    key: 'TimeLastModified',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'Operate',
    key: 'Operate',
    align: 'center',
    render(text, recod: any) {
      const dispUrl = ListGUID.DocumentLink;      
      
      return (
        <div>
          <a href={ListGUID.Domain+ListGUID.SiteRelativeUrl+'/_layouts/download.aspx?SourceUrl='+ListGUID.Domain+recod.ServerRelativeUrl}>下载</a>
        </div>
      )
    },
  },
  
]

// 测试代码，调试API使用
class DocumentLibrary extends React.Component<FormComponentProps> {
  constructor(props: any & FormComponentProps) {
    super(props); 
  }

  handleSelectChange = value => {
    
    this.props.form.setFieldsValue({
      note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
    });
  };
  
  state = {
    isLoading: true,
    treeData: [], //目录
    file_data: [],
    totalnum: 0,
    LinkUrl: "", // 要打开的文档库url地址
    DocumentButtonIsHidden: true,
    IsFW: false
  }
  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission();
    // let changeLog = await Api.getChangeLog('ContractLib');
    // 
    
    

    let IsFW = await Api._isLegalDepartment();
    this.setState({ IsFW });
    
    this.getFolder(); //获取目录
    // this.getTest();// 测试代码，调试API使用
  }
  
  public render(): React.ReactElement {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className='box'>
        <div className='box_content'>
          <div className="top"></div>

          <div className="box_c">
            <Row>
              <Col span={19} push={5}>
                <div className="flex_d">
                  <div className="placeholder">
                  文档库 <Button hidden={this.state.DocumentButtonIsHidden} type="primary" onClick={() => {window.open(ListGUID.Domain+this.state.LinkUrl)}}>打开文档库</Button>
                  </div>
                  <div className="d_wj">
                    <div className="file">
                    <Table columns={columns} dataSource={this.state.file_data}
                      pagination={{
                        hideOnSinglePage: false,
                        total: this.state.totalnum,
                        pageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        defaultCurrent: 1,
                        showTotal: function (total) {
                          return `总共有 ${total} 条数据`;
                        }
                      }}  />
                    </div>
                  </div>
                </div>
              </Col>
              <Col span={5} pull={19}>
                <Spin spinning={this.state.isLoading}>
                  <div className="tree_border">
                    <DirectoryTree multiple onSelect={this.onSelect} onExpand={this.onExpand} treeData={this.state.treeData}>
                      
                    </DirectoryTree>
                  </div>
                </Spin>
                
              </Col>
            </Row>
          </div>

        </div>
      </div>
    )

  }

  public async getFolder(){

    let treeData = []; 
    if(this.state.IsFW){
      treeData = 
      [
        {
          "title": "合同台账库",
          "name": "StandingBook",
          "key": "0-0",
          "children": [{'title': '加载中...'}],
          "UrlName": "ContractLib",
          "Guid": ListGUID.StandingBook,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/ContractLib'
        },
        {
          "title": "合同申请书",
          "key": "0-1",
          "name": "ContractPetitionLib",
          "children": [{'title': '加载中...'}],
          "UrlName": "ContractPetitionLib",
          "Guid": ListGUID.Petition,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/ContractPetitionLib',
          "ItemBelong": 0
        },
        {
          "title": "规章制度库",
          "key": "0-2",
          "name": "Regulations",
          "children": [{'title': '加载中...'}],
          "UrlName": "RegulationsLib",
          "Guid": ListGUID.Regulations,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/RegulationsLib'
        },
        {
          "title": "规章制度申请书",
          "key": "0-3",
          "name": "RegulationsPetitionLib",
          "children": [{'title': '加载中...'}],
          "UrlName": "RegulationsPetitionLib",
          "Guid": ListGUID.Petition,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/RegulationsPetitionLib',
          "ItemBelong": 1
        },
        {
          "title": "案件管理库",
          "key": "0-4",
          "name": "CaseManagement",
          "children": [{'title': '加载中...'}],
          "UrlName": "CaseLib",
          "Guid": ListGUID.CaseManagement,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/CaseLib'
        },
        {
          "title": "通用文档库",
          "key": "0-5",
          "children": [{'title': '加载中...'}],
          "UrlName": "CommonLib",
          "Guid": ListGUID.CommonLib,
          "LinkUrl": ListGUID.SiteRelativeUrl+'/CommonLib'
        },
      ];
    }else{
      treeData = 
    [
      {
        "title": "合同申请书",
        "key": "0-0",
        "name": "ContractPetitionLib",
        "children": [{'title': '加载中...'}],
        "UrlName": "ContractPetitionLib",
        "Guid": ListGUID.Petition,
        "LinkUrl": ListGUID.SiteRelativeUrl+'/ContractPetitionLib',
        "ItemBelong": 0
      },
      {
        "title": "规章制度申请书",
        "key": "0-1",
        "name": "RegulationsPetitionLib",
        "children": [{'title': '加载中...'}],
        "UrlName": "RegulationsPetitionLib",
        "Guid": ListGUID.Petition,
        "LinkUrl": ListGUID.SiteRelativeUrl+'/RegulationsPetitionLib',
        "ItemBelong": 1
      },
      {
        "title": "通用文档库",
        "key": "0-2",
        "children": [{'title': '加载中...'}],
        "UrlName": "CommonLib",
        "Guid": ListGUID.CommonLib,
        "LinkUrl": ListGUID.SiteRelativeUrl+'/CommonLib'
      },
    ];
    }
    
    let guids = this.state.IsFW ? [ListGUID.StandingBook,ListGUID.Petition, ListGUID.Regulations, ListGUID.CaseManagement, ListGUID.CommonLib] : [ListGUID.Petition, ListGUID.CommonLib]
    let checkYear = await dynamicsService.GetCheckYear({Email: JSON.parse(sessionStorage.getItem('userInfo')).Email, Guid: guids});
    for(let i in checkYear.data) {
      treeData.forEach(j => {
        if(j.name === i) {
          j.children = [];
          let keys = Object.keys(checkYear.data[i]);
          keys = keys.sort((m:any,n:any) => Number(n) - Number(m))
          keys.forEach((k, index) => {
            j.children.push({
              title: k,
              key: j.key + '-' + index,
              children:  [{ 'title': '加载中...' }],
              UniqueId: '',
              Path: '',
              Guid: j.Guid,
              LinkUrl: j.LinkUrl + '/' + k
            })
          })
        }
      })
      
    }
    console.log(checkYear)
    console.log(treeData, 'treeData')

    this.setState({ treeData,isLoading: false })
    
  }

  
  onSelect = async  (keys, event) => {
    // 
    // 
    let folder_key = event.node.props.eventKey.split('-');
    let count = folder_key.length - 1; //目录层数

    if(count == 4){
      let son_file = await Api.getFileByFolder(event.node.props.UniqueId);
      // 

      if(son_file.length == 0){ 
        this.setState({ file_data: son_file, totalnum: son_file.length });
        return ; 
      } 

      const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      
      // 拼接第四层文件
      let l = 0;
      let file_data = [];
      for(let i = 0; i<son_file.length; i++){
        // let permission_names = event.node.props.permission_title.filter(function(item, index){ return item.Names != null ? item.Names.replace(/^\s*|\s*$/g,"").split(';').indexOf(son_file[i].Name) > -1 : false });  // 筛选文件名
        if(event.node.props.permission_title.length > 0){ 
          file_data.push({
            Name: son_file[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + folder_key[3] + '-' + folder_key[4] + '-' + l,
            UniqueId: son_file[i].UniqueId,
            isLeaf: true,
            file_url: son_file[i].LinkingUri,
            ServerRelativeUrl: son_file[i].ServerRelativeUrl,
            TimeLastModified: this.changeDate(son_file[i].TimeLastModified)
          });
          l++;
          // son_file[i].TimeLastModified = this.changeDate(son_file[i].TimeLastModified);
        }
      }

      // treeData[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children[folder_key[4]].children = [];

      this.setState({ treeData, file_data: file_data, totalnum: file_data.length });
      
      
      return ;
    }


    if(event.node.props.file_url){
      window.open(ListGUID.DocumentLink+'?sourcedoc='+event.node.props.UniqueId);
      return ;
    }

  };

  onExpand = async (keys, event) => {    
    // 
    // return ;
    console.log(event)
    let folder_key = event?.node?.props?.eventKey?.split('-') || [];
    let count = folder_key.length > 0 ? folder_key.length - 1 : 0; //目录层数

    if(this.state.IsFW == true && event.node != undefined && event.node.props.LinkUrl){
      this.setState({ LinkUrl: event.node.props.LinkUrl, DocumentButtonIsHidden: false }); //初始化本次打开的文档库路径
    }
    this.setState({file_data: [], totalnum: 0 });
    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 关闭当前节点的子节点 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓//
    if(event.length == 0){ 
      return ;
    }
    let tree_keys = keys;
    if(!event.expanded){
      if(count && count !== 1) {
        for(let i = 0;i<keys.length;i++){
          if(tree_keys[i] != '' && tree_keys[i].substring(0, event.node.props.eventKey.length) == event.node.props.eventKey){
            
            tree_keys.splice(i, 1);
            i--;
          }
        }
        
        this.onExpand(tree_keys, []); //关闭子节点
        this.setChildrenNull(event.node.props.pos); //当前节点的子节点设为null
      }
      
      return ;
    }
    //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 关闭当前节点的子节点 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑//

    // 
    

    
    // 如果点击的是通用文档库就跳到另一个单独的方法
    if(event.node.props.UrlName == 'CommonLib'){
      this.CommonLib(keys, event, folder_key, count);
      return ;
    }

    
    // 顶级目录
    if(count == 1){ // 
      // const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      // let folder:any;
      // folder = await Api.getFolder(event.node.props.UrlName); // 文档库顶级目录
      // folder = folder.filter(function(item, index){ return item.Name != 'Forms' });
      
      
      // // return ;
 
      // // 根据列表Guid查权限 
      // // let Naturcontract:any;
      // // if (event.node.props.UrlName == 'ContractPetitionLib'){
      // //   Naturcontract = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":0}]}] });
      // //   // Naturcontract = Naturcontract.filter(function(item, index){ return item.ItemBelong == event.node.props.ItemBelong });
      // // }else if(event.node.props.UrlName == 'RegulationsPetitionLib'){
      // //   Naturcontract = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":"1"}]}]});
      // // }else{
      // //   Naturcontract = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1});
      // // }
      // // 
      
      // // let permission_data = Naturcontract.data;
      // // 

      // let children = [];
      // let _this = this;
      // let year:any;
      
      // // await folder.forEach(async function(item, index){
      // //   if (event.node.props.UrlName == 'ContractPetitionLib'){
      // //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":0},{"key":"SRUrls","filterType":"substringof","value":"ContractPetitionLib/"+item.Name+"/"}]}] });
      // //   }else if(event.node.props.UrlName == 'RegulationsPetitionLib'){
      // //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":"1"},{"key":"SRUrls","filterType":"substringof","value":"RegulationsPetitionLib/"+item.Name+"/"}]}]});
      // //   }else{
      // //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"FileAddress","filterType":"substringof","value":""+ item.Name +"/"}]}] });
      // //   }
      // //   
      // //   
        
      // //   if(year.data.length > 0){
      // //     children.push({
      // //       title: item.Name,
      // //       key: 0 + '-' + folder_key[count] + '-',
      // //       children: item.ItemCount == 0 ? [] : [{ 'title': '加载中...' }],
      // //       UniqueId: item.UniqueId,
      // //       Path: item.Name,
      // //       Guid: event.node.props.Guid,
      // //       LinkUrl: item.ServerRelativeUrl
      // //     });
      // //   }
      // //   // if(folder.length == index+1){
      // //   //   

      // //   //   children.sort(function (a,b){
      // //   //     return b.title-a.title; 
      // //   //   })
      // //   //   for (let i = 0; i < children.length; i++) {
      // //   //     children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      // //   //   }
      // //   //   treeData[folder_key[count]].children = children;
      // //   //   _this.setState({ treeData });
      // //   //   
      // //   // }
      // // })
      // console.log(folder, event)
      // for(let i = 0; i < folder.length; i ++) {
      //   if (event.node.props.UrlName == 'ContractPetitionLib'){
      //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":0},{"key":"SRUrls","filterType":"substringof","value":"ContractPetitionLib/"+folder[i].Name+"/"}]}] });
      //   }else if(event.node.props.UrlName == 'RegulationsPetitionLib'){
      //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":"1"},{"key":"SRUrls","filterType":"substringof","value":"RegulationsPetitionLib/"+folder[i].Name+"/"}]}]});
      //   }else{
      //     year = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 1, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"FileAddress","filterType":"substringof","value":""+ folder[i].Name +"/"}]}] });
      //   }
        
        
        
      //   if(year.data.length > 0){
      //     children.push({
      //       title: folder[i].Name,
      //       key: 0 + '-' + folder_key[count] + '-',
      //       children: folder[i].ItemCount == 0 ? [] : [{ 'title': '加载中...' }],
      //       UniqueId: folder[i].UniqueId,
      //       Path: folder[i].Name,
      //       Guid: event.node.props.Guid,
      //       LinkUrl: folder[i].ServerRelativeUrl
      //     });
      //   }
      // }
      

      // children.sort(function (a,b){
      //   return b.title-a.title; 
      // })
      
      // for (let i = 0; i < children.length; i++) {
      //   children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      // }
      // treeData[folder_key[count]].children = children;
      // _this.setState({ treeData });
      



      // // for(let i=0; i<folder.length;i++){
      // //   let permission_year = [] // 先筛选年份的权限数据
      // //   if(event.node.props.UrlName == 'ContractPetitionLib'){ // 筛选合同申请书的年份
      // //     permission_year = await permission_data.filter(function(item, index){ return item.SRUrls ? item.SRUrls.split('/')[1] == folder[i].Name && item.ItemBelong == 0 : false });
      // //   }else if(event.node.props.UrlName == 'RegulationsPetitionLib'){ // 筛选规章制度申请书的年份
      // //     permission_year = await permission_data.filter(function(item, index){ return item.SRUrls ? item.SRUrls.split('/')[1] == folder[i].Name && item.ItemBelong == 1 : false });
      // //   }else{ // 筛选合同申请、规章制度申请、案件管理申请的年份
      // //     permission_year = await permission_data.filter(function(item, index){ return item.FileAddress ? item.FileAddress.split('/')[0] == folder[i].Name : false });
      // //   }
        
      // //   if(folder[i].Name != "Forms" && permission_year.length > 0){
      // //     children.push({ 
      // //       title: folder[i].Name, 
      // //       key: 0 + '-' + folder_key[count] + '-' + l, 
      // //       children: folder[i].ItemCount == 0 ? [] : [{'title': '加载中...'}],
      // //       UniqueId: folder[i].UniqueId,
      // //       permission_year: permission_year,
      // //       LinkUrl: folder[i].ServerRelativeUrl
      // //     });
      // //     l++;
      // //   }
      // // }

      
      return ;
    }

    // 当前点击的子目录
    let son_folder = await Api.getSonFolder1(event.node.props.LinkUrl);
    

    //////////////////////////////////// 加载第三层目录 ////////////////////////////////////
    if(count == 2){
      const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      

      // 拼接第三层目录
      
      let children = [];
      let _this = this;
      let company:any;
      let company_data = [];
      if (event.node.props.LinkUrl.indexOf('ContractPetitionLib') > -1){
        company = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":0},{"key":"SRUrls","filterType":"substringof","value":"ContractPetitionLib/"+event.node.props.title+"/"}]}] });
      }else if(event.node.props.LinkUrl.indexOf('RegulationsPetitionLib') > -1){
        company = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":"1"},{"key":"SRUrls","filterType":"substringof","value":"RegulationsPetitionLib/"+event.node.props.title+"/"}]}]});
      }else{
        company = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"FileAddress","filterType":"substringof","value":""+event.node.props.title+"/"}]}] });
      }
      son_folder.forEach(async function(folderItem, index){
        // 
        
        if(event.node.props.LinkUrl.indexOf('ContractPetitionLib') > -1 || event.node.props.LinkUrl.indexOf('RegulationsPetitionLib') > -1){ // 筛选合同申请书和规章制度申请书的编号
          company_data = company.data.filter(function(item, index){ return item.SRUrls ? item.SRUrls.indexOf('/'+folderItem.Name+'/') > -1 : false });
        }else{ // 筛选筛选合同编号、筛选规章制度和案件管理的编号
          company_data = company.data.filter(function(item, index){ return item.FileAddress ? item.FileAddress.indexOf('/'+folderItem.Name+'/') > -1  : false });
        }
        
        
        
        if(company_data.length > 0){
          children.push({
            title: folderItem.Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-',   
            children: !folderItem.ItemCount || folderItem.ItemCount == 0 ? [] : [{'title': '加载中...'}],
            UniqueId: folderItem.UniqueId,
            expandAction: true,
            Path: event.node.props.title+"/"+folderItem.Name+"/",
            Guid: event.node.props.Guid,
            LinkUrl: folderItem.ServerRelativeUrl
          })
          
        }
        if(son_folder.length == index+1){

          children.sort(function(a, b){
            if(a.title < b.title) return -1;
            if(a.title > b.title) return 1;
          })

          for (let i = 0; i < children.length; i++) {
            children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
          }

          
          
          
          treeData[folder_key[1]].children[folder_key[2]].children = children;
          
          _this.setState({ treeData });
          
        }
      })

      // for(let i = 0; i<son_folder.length; i++){
      //   let permission_our = [] // 根据上一步筛选的年份权限数据中再筛选公司数据
      //   if(treeData[folder_key[1]].UrlName == 'ContractPetitionLib' || treeData[folder_key[1]].UrlName == 'RegulationsPetitionLib'){ // 筛选合同申请书和规章制度申请书的公司
      //     permission_our = event.node.props.permission_year.filter(function(item, index){ return item.SRUrls ? item.SRUrls.split('/')[2] == son_folder[i].Name : false });
      //   }else{
      //     permission_our = event.node.props.permission_year.filter(function(item, index){ return item.FileAddress ? item.FileAddress.split('/')[1] == son_folder[i].Name : false });
      //   }
      //   // 
        
      //   if(permission_our.length > 0){
      //     children.push({
      //       title: son_folder[i].Name, 
      //       key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + l,   
      //       children: son_folder[i].ItemCount == 0 ? [] : [{'title': '加载中...'}],
      //       UniqueId: son_folder[i].UniqueId,
      //       expandAction: true,
      //       permission_our: permission_our,
      //       LinkUrl: son_folder[i].ServerRelativeUrl
      //     })
      //     l++;
      //   }
      // }
      
      return ;
    }

    //////////////////////////////////// 加载第四层目录 ////////////////////////////////////
    if(count == 3){
      const treeData3 = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      

      // 拼接第四层编号目录
      let children3 = [];

      let number_data:any;
      if (event.node.props.LinkUrl.indexOf('ContractPetitionLib') > -1){
        number_data = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":0},{"key":"SRUrls","filterType":"substringof","value":"ContractPetitionLib/"+event.node.props.Path}]}] });
      }else if(event.node.props.LinkUrl.indexOf('RegulationsPetitionLib') > -1){
        number_data = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"ItemBelong","filterType":"eq","value":"1"},{"key":"SRUrls","filterType":"substringof","value":"RegulationsPetitionLib/"+event.node.props.Path}]}]});
      }else{
        number_data = await Api._getPaged({Guid: event.node.props.Guid, PageSize: 100000, PageIndex: 1, FilterL:  [{"logic":"and","where":[{"key":"FileAddress","filterType":"substringof","value":""+event.node.props.Path}]}] });
      }

      for(let i = 0; i<son_folder.length; i++){ 
        let permission_title = []  // 筛选编号

        if(event.node.props.LinkUrl.indexOf('ContractPetitionLib') > -1 || event.node.props.LinkUrl.indexOf('RegulationsPetitionLib') > -1){ // 筛选合同申请书和规章制度申请书的编号
          permission_title = number_data.data.filter(function(item, index){ return item.SRUrls ? item.SRUrls.split('/')[3] == son_folder[i].Name : false });
        }else{ // 筛选筛选合同编号、筛选规章制度和案件管理的编号
          permission_title = number_data.data.filter(function(item, index){ return item.FileAddress ? item.FileAddress.split('/')[2] == son_folder[i].Name : false });
        }

        if(permission_title.length > 0){
          children3.push({
            title: son_folder[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + folder_key[3] + '-',   
            children: [],
            UniqueId: son_folder[i].UniqueId,
            expandAction: true,
            permission_title: permission_title,
            LinkUrl: son_folder[i].ServerRelativeUrl
          })
        }
      }

      children3.sort(function(a, b){
        if(a.title < b.title) return -1;
        if(a.title > b.title) return 1;
      })

      for (let i = 0; i < children3.length; i++) {
        children3[i].key = children3[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      }

      treeData3[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children = children3;
      
      this.setState({ treeData: treeData3 });
      
      
      return ;
    }


    //////////////////////////////////// 加载第五层文件 ////////////////////////////////////
    if(count == 4){
      return ; // 只OnSelect方法调用文件数据就好, 因为OnSelect可以监听到文件夹关闭和打开两种状态
      let son_file = await Api.getFileByFolder(event.node.props.UniqueId);
      

      if(son_file.length == 0){ 
        this.setState({ file_data: son_file, totalnum: son_file.length });
        return ; 
      } 

      const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      
      // 拼接第四层文件
      let l = 0;
      let file_data = [];
      for(let i = 0; i<son_file.length; i++){
        let permission_names = event.node.props.permission_title.filter(function(item, index){ return item.Names != null ? item.Names.replace(/^\s*|\s*$/g,"").split(';').indexOf(son_file[i].Name) > -1 : false });  // 筛选文件名
        if(permission_names.length > 0){ 
          file_data.push({
            Name: son_file[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + folder_key[3] + '-' + folder_key[4] + '-' + l,
            UniqueId: son_file[i].UniqueId,
            isLeaf: true,
            file_url: son_file[i].LinkingUri,
            ServerRelativeUrl: son_file[i].ServerRelativeUrl,
            TimeLastModified: this.changeDate(son_file[i].TimeLastModified)
          });
          l++;
          // son_file[i].TimeLastModified = this.changeDate(son_file[i].TimeLastModified);
        }
      }

      // treeData[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children[folder_key[4]].children = [];

      this.setState({ treeData, file_data: file_data, totalnum: file_data.length });
      
      
      return ;
    }
  };

  public setChildrenNull(keys){
    // 
    let folder_key = keys.split('-');
    let count = folder_key.length - 1; //目录层数
    let _this = this;
    const treeData = [...this.state.treeData];

    setTimeout(function(){
      switch(count){
        case 1:
          treeData[folder_key[count]].children = [{title: '加载中...'}];
          _this.setState({ treeData });
          break;
        case 2:
          treeData[folder_key[1]].children[folder_key[2]].children = [{title: '加载中...'}];
          _this.setState({ treeData });
          break;  
        case 3:
          treeData[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children = [{title: '加载中...'}];
          _this.setState({ treeData });
          break;
        case 4:
  
          break;
        case 5:
  
          break;
      }
    },500);
  }


  // 通用文档库
  public async CommonLib(keys, event, folder_key, count){
    this.getFileData(event);
    // 顶级目录
    if(count == 1){ // 
      const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新

      let folder = await Api.getFolder(event.node.props.UrlName); // 文档库顶级目录
      

      let l = 0; // 有时候Name为Forms的目录不在数组末尾，而是在第一个，会打乱i的顺序以至于i从1开始而不是从0
      let children = [];
      for(let i=0; i<folder.length;i++){
        
        if(folder[i].Name != "Forms"){
          children.push({ 
            title: folder[i].Name, 
            key: 0 + '-' + folder_key[count] + '-', 
            children: folder[i].ItemCount == 0 ? [] : [{'title': '加载中...'}],
            UniqueId: folder[i].UniqueId,
            UrlName: event.node.props.UrlName,
            LinkUrl: folder[i].ServerRelativeUrl,
          });
          l++;
        }
      }

      children.sort(function(a, b){
        if(a.title < b.title) return -1;
        if(a.title > b.title) return 1;
      })

      for (let i = 0; i < children.length; i++) {
        children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      }

      treeData[folder_key[count]].children = children;
      this.setState({ treeData });
      
      return ;
    }

    // 当前点击的子目录
    let son_folder = await Api.getSonFolder(event.node.props.UniqueId);
    

    //////////////////////////////////// 加载第三层目录 ////////////////////////////////////
    if(count == 2){
      const treeData = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      

      // 拼接第三层目录
      let l = 0;
      let children = [];
      for(let i = 0; i<son_folder.length; i++){
        
          children.push({
            title: son_folder[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-',   
            children: son_folder[i].ItemCount == 0 ? [] : [{'title': '加载中...'}],
            UniqueId: son_folder[i].UniqueId,
            expandAction: true,
            UrlName: event.node.props.UrlName,
            LinkUrl: son_folder[i].ServerRelativeUrl,
          })
          l++;
      }

      children.sort(function(a, b){
        if(a.title < b.title) return -1;
        if(a.title > b.title) return 1;
      })

      for (let i = 0; i < children.length; i++) {
        children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      }

      treeData[folder_key[1]].children[folder_key[2]].children = children;
      
      this.setState({ treeData });
      
      
      return ;
    }

    //////////////////////////////////// 加载第四层目录 ////////////////////////////////////
    if(count == 3){
      const treeData3 = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      

      // 拼接第四层目录
      let l = 0;
      let children3 = [];
      for(let i = 0; i<son_folder.length; i++){
          children3.push({
            title: son_folder[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + folder_key[3] + '-',   
            children: son_folder[i].ItemCount == 0 ? [] : [{'title': '加载中...'}],
            UniqueId: son_folder[i].UniqueId,
            expandAction: true,
            UrlName: event.node.props.UrlName,
            LinkUrl: son_folder[i].ServerRelativeUrl,
          })
          l++;
      }
      
      children3.sort(function(a, b){
        if(a.title < b.title) return -1;
        if(a.title > b.title) return 1;
      })

      for (let i = 0; i < children3.length; i++) {
        children3[i].key = children3[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      }

      treeData3[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children = children3;
      
      this.setState({ treeData: treeData3 });
      
      
      return ;
    }


    //////////////////////////////////// 加载第四层目录 ////////////////////////////////////
    if(count == 4){
      const treeData3 = [...this.state.treeData]; // 必须这样取值，要不然重新setState时页面不会刷新
      

      // 拼接第四层目录
      let l = 0;
      let children = [];
      for(let i = 0; i<son_folder.length; i++){
          children.push({
            title: son_folder[i].Name, 
            key: 0 + '-' + folder_key[1] + '-' + folder_key[2] + '-' + folder_key[3] + '-' + folder_key[4] + '-',   
            children: [],
            UniqueId: son_folder[i].UniqueId,
            expandAction: true,
            UrlName: event.node.props.UrlName,
            LinkUrl: son_folder[i].ServerRelativeUrl,
          })
          l++;
      }
      
      children.sort(function(a, b){
        if(a.title < b.title) return -1;
        if(a.title > b.title) return 1;
      })

      for (let i = 0; i < children.length; i++) {
        children[i].key = children[i].key + i; // 排序后给key最后一位赋值，不这样操作key和数组的key就对不上，给treeData赋值时就会导致打开的是这个文件夹但是数据却出现在了另外的文件夹下
      }

      treeData3[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children[folder_key[4]].children = children;
      
      this.setState({ treeData: treeData3 });
      
      
      return ;
    }
    
  }

  public async getFileData(event){
    let son_file = [];

    if(!event.node.props.UniqueId){
      
      son_file = await Api._getFolderByServerRelativePath(event.node.props.UrlName);
    }else{
      son_file = await Api.getFileByFolder(event.node.props.UniqueId);
    }

    if(son_file.length == 0){ 
      this.setState({ file_data: son_file, totalnum: son_file.length });
      return ; 
    } 
    // 拼接第四层文件
    // let l = 0;
    // let children = [];
    for(let i = 0; i<son_file.length; i++){
        son_file[i].TimeLastModified = this.changeDate(son_file[i].TimeLastModified);
    }

    // treeData[folder_key[1]].children[folder_key[2]].children[folder_key[3]].children[folder_key[4]].children = [];

    this.setState({file_data: son_file, totalnum: son_file.length });
    
    
  }

  public changeDate(dateA) {
 
    var dateee = new Date(dateA).toJSON();
    
    var date = new Date(+new Date(dateee)+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
    
    return date;
  };

  //访问list
  public async getTest() {
    // 测试代码，调试API使用
    let items = await Api.GetListItemsByListGUID(ListGUID.StandingBook);
    // 
  }
}
export default Form.create()(DocumentLibrary);